<script setup>
  import { ref, reactive, onMounted } from 'vue'
  import userApi from '@/apis/user'
  import { userStores } from '@/stores/user.js'
  // 表单元素的 ref 属性
  const accountForm = ref()
  // 设置响应式数据
  const formData = reactive({
    account: 'zyc123',
    password: '123456',
  })
  // 定义表单数据验证规则
  const accountRules = reactive({
    account: {
      rules: [
        { required: true, errorMessage: '请输入登录账号' },
        { pattern: '^[a-zA-Z0-9]{6,8}$', errorMessage: '登录账号格式不正确' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '请输入登录密码' },
        { pattern: '^\\d{6}$', errorMessage: '登录密码格式不正确' },
      ],
    },
  })
  async function onFormSubmit() {
    try {
      // 验证通过
      const formData = await accountForm.value.validate()
      // 表单的数据
      // console.log(formData)
      // 调用登录接口
      const { data } = await userApi.login(formData)
      // 记录用户登录成功后的状态
      const user = userStores()
      user.token = data //持久化token
      // 跳转到task页面
      uni.utils.toast('登入成功')
      uni.switchTab({ url: '/pages/task/index' })
    } catch (err) {
      // 验证失败
      console.log(err)
    }
  }
</script>

<template>
  <uni-forms
    class="login-form"
    :model="formData"
    ref="accountForm"
    :rules="accountRules"
  >
    <uni-forms-item name="account">
      <input
        type="text"
        placeholder="请输入账号"
        v-model="formData.account"
        class="uni-input-input"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <input
        type="text"
        placeholder="请输入密码"
        v-model="formData.password"
        class="uni-input-input"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <button class="submit-button" @click="onFormSubmit">登录</button>
  </uni-forms>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
